package com.cqs.leetcode;

import java.util.HashMap;
import java.util.Map;

public class IsomorphicStrings {

    public boolean isIsomorphic(String s, String t) {
        if (s == null && t == null) return true;
        if (s == null || t == null) return false;
        if (s.length() != t.length()) return false;
//        if (s.equals(t)) return true;

        Map<Character,Integer> map1 = new HashMap<>();
        Map<Character,Integer> map2 = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            Integer pos1  = map1.get(s.charAt(i));
            Integer pos2 = map2.get(t.charAt(i));
            if (!sameIndex(pos1,pos2)) {
                return false;
            }
            if (pos1 == null) {
                map1.put(s.charAt(i),i);
                map2.put(t.charAt(i),i);
            }
        }
        return true;
    }

    private boolean sameIndex(Integer pos1,Integer pos2){
        if (pos1 == null && pos2 == null) return true;
        if (pos1 != null){
            return pos1.equals(pos2);
        }
        return false;
    }

    public static void main(String[] args) {
        IsomorphicStrings is = new IsomorphicStrings();
        System.out.println(is.isIsomorphic( "egg", "add"));
        System.out.println(is.isIsomorphic( "foo", "bar"));
        System.out.println(is.isIsomorphic( "paper", "title"));
    }
}
